import { instructAttachmentPreview } from '@/services/api/api-instruct-attachment';
import { selectRecord } from '@/services/api/api-pressconference';
import { CheckOutlined, CopyOutlined, DownloadOutlined } from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { WaterMark } from '@ant-design/pro-layout';
import { useAccess, useModel } from '@umijs/max';
import {
  Alert,
  Button,
  Descriptions,
  Divider,
  Flex,
  Image,
  message,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import AddReceipt from '../receipt/AddReceipt';
import ListReceipt from '../receipt/ListReceipt';
import ReceiptAssign from '../receipt/ReceiptAssign';
interface DetailsRecordProps {
  item: PressconferenceData.RecordPage;
  onClose: () => void;
}

const DetailsRecord: React.FC<DetailsRecordProps> = ({ item, onClose }) => {
  const { initialState } = useModel('@@initialState');

  const ref = useRef<ProFormInstance>();

  const access = useAccess();

  const [record, setRecordState] = useState<PressconferenceData.RecordSelect>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);

  const [reload, setReloadState] = useState(false);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };

  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const loadSelectRecord = async () => {
    try {
      const response = await selectRecord({ id: item.id });
      if (response.code === 0) {
        setRecordState(response.data);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      open={drawerFormVisible}
      key={`drawer_form_detail_record_${item.id}`}
      title={
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            {record?.run === 2 ? <Tag color="red">已结束</Tag> : ''}
            <span>{record?.name}</span>
          </div>
        </div>
      }
      trigger={
        <Typography.Text ellipsis={true} style={{ width: 200 }}>
          <a key="a_detail_record">{item?.name} </a>
        </Typography.Text>
      }
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: '800px',
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            // ...defaultDoms,

            access.新闻发布x配置x接收者 && record?.isReply == 0 && (
              <AddReceipt recordId={record?.id} onSave={function (): void {}} />
            ),
          ];
        },
      }}
      onOpenChange={(visible) => {
        if (visible) {
          window.parent.postMessage({ message: '阅读情况改变' }, '*');
          setReloadState(!reload);
          loadSelectRecord();
        } else {
          onClose();
          setRecordState(undefined);
        }
        setDrawerFormVisible(visible);
      }}
    >
      <Spin spinning={record ? false : true}>
        <WaterMark content={`新闻发布 - ${initialState?.currentUser?.name}`}>
          <>
            {record && (
              <>
                <Descriptions>
                  <Descriptions.Item label="创建时间">{record?.createdTime}</Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="发布单位">
                    {record?.createdOrganizationName}
                  </Descriptions.Item>
                  <Descriptions.Item label="发布人">{record?.createdAccountName}</Descriptions.Item>
                  <Descriptions.Item label="联系方式">
                    {record?.createdAccountPhone}
                  </Descriptions.Item>
                </Descriptions>
                {access.宣传指令x配置x管理员 ? (
                  <Descriptions>
                    <Descriptions.Item label="阅读和回复">
                      {
                        <ReceiptAssign
                          id={record?.id}
                          deadlineTime={record?.deadlineTime}
                          receipt={'点击查看详情'}
                          type={'read'}
                          isRun={record?.run == 1}
                        />
                      }
                    </Descriptions.Item>
                  </Descriptions>
                ) : (
                  <></>
                )}
                <Divider
                  orientation="left"
                  style={{
                    fontWeight: 600,
                    fontSize: 14,
                  }}
                >
                  发布会信息
                </Divider>
                <Descriptions>
                  <Descriptions.Item label="截止时间">
                    <span
                      style={{
                        color: record.run == 1 ? 'green' : 'red',
                      }}
                    >
                      {record?.deadlineTime}
                    </span>
                  </Descriptions.Item>
                  <Descriptions.Item label="发布会时间">
                    {record?.startTime} - {record?.endTime}
                  </Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="地点">{record?.location}</Descriptions.Item>
                </Descriptions>
                <Divider
                  orientation="left"
                  style={{
                    fontWeight: 600,
                    fontSize: 14,
                  }}
                >
                  内容
                </Divider>
                {record?.name ? (
                  <Typography.Title
                    copyable={{
                      icon: [
                        <CopyOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copy-icon"
                        />,
                        <CheckOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copied-icon"
                        />,
                      ],
                    }}
                    level={3}
                    style={{ textAlign: 'center' }}
                  >
                    {record?.name}
                  </Typography.Title>
                ) : (
                  <Typography.Title level={3} style={{ textAlign: 'center' }}>
                    暂无标题
                  </Typography.Title>
                )}
                <Flex justify={'flex-end'} align={'center'}>
                  <Typography.Paragraph
                    copyable={{
                      icon: [
                        <Tag color="#108ee9" key="copy-icon">
                          复制全文
                        </Tag>,
                        <CheckOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copied-icon"
                        />,
                      ],
                      text: async () =>
                        new Promise((resolve) => {
                          var tempDivElement = document.createElement('div');
                          tempDivElement.innerHTML = record?.content;
                          resolve(tempDivElement.textContent || tempDivElement.innerText || '');
                        }),
                    }}
                  />
                </Flex>

                <div
                  dangerouslySetInnerHTML={{
                    __html: `${record?.content}`,
                  }}
                />
                <Divider
                  orientation="left"
                  style={{
                    fontWeight: 600,
                    fontSize: 14,
                  }}
                >
                  问题
                </Divider>
                <Typography.Paragraph style={{ flexGrow: 1, margin: 0 }} type="secondary">
                  <blockquote>{record.problem}</blockquote>
                </Typography.Paragraph>

                {record?.attachments && record?.attachments.length > 0 && (
                  <>
                    <Divider />
                    <div
                      style={{
                        textAlign: 'right',
                      }}
                    >
                      <Button
                        type="primary"
                        key="import"
                        size="small"
                        icon={<DownloadOutlined />}
                        onClick={() => {
                          record?.attachments.forEach(function (item) {
                            window.open(item.content, '_blank');
                          });
                        }}
                      >
                        全部下载
                      </Button>
                    </div>

                    <Upload
                      listType="picture"
                      multiple
                      fileList={record?.attachments.map((item) => {
                        return {
                          uid: item.id,
                          name: item.name,
                          url: item.content,
                          mimeType: item.mimeType,
                          status: 'done',
                        };
                      })}
                      showUploadList={{
                        downloadIcon: (
                          <div
                            style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}
                          >
                            <DownloadOutlined
                              style={{
                                marginRight: '10px',
                              }}
                            />
                            点击下载
                          </div>
                        ),
                        showRemoveIcon: false,
                        showDownloadIcon: true,
                      }}
                      onPreview={async (file: UploadFile) => {
                        setPreviewData({
                          id: file.uid,
                          name: file.name,
                          mimeType: file.mimeType,
                          url: file.url,
                        });
                        setPreviewOpen(true);
                      }}
                    />
                    <DrawerForm
                      title={previewData?.name}
                      drawerProps={{
                        width: 900,
                        destroyOnClose: true,
                      }}
                      open={previewOpen}
                      onOpenChange={async (visible) => {
                        if (visible) {
                          if (
                            previewData?.mimeType !== null &&
                            previewData?.mimeType?.indexOf('image') > -1
                          ) {
                            //图片预览
                          } else {
                            setPreviewLoading(true);
                            const response = await instructAttachmentPreview({
                              id: previewData?.id,
                            });

                            if (response.code === 0) {
                              setPreviewOnlineUrl(response.data);
                            } else {
                              message.error('暂时无法预览');
                              setPreviewLoading(false);
                            }
                          }
                        } else {
                          setPreviewOpen(false);
                          setPreviewData(undefined);
                          setPreviewOnlineUrl(undefined);
                        }
                      }}
                      submitter={{
                        searchConfig: {
                          submitText: '下载',
                        },
                      }}
                      onFinish={async (values) => {
                        window.open(previewData?.url, '_blank');
                      }}
                    >
                      <Alert
                        style={{
                          marginBottom: 20,
                        }}
                        message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                        type="warning"
                        showIcon
                      />
                      {previewData?.mimeType !== null &&
                      previewData?.mimeType?.indexOf('image') > -1 ? (
                        <Image width="100%" src={previewData?.url} />
                      ) : (
                        <Spin spinning={previewLoading}>
                          <iframe
                            ref={iframeRef}
                            src={previewOnlineUrl}
                            height={windowSize.innerHeight - 220}
                            width="100%"
                            frameBorder="0"
                            // scrolling="false"
                            allowFullScreen={true}
                            // scrolling={'no'}
                          />
                        </Spin>
                      )}
                    </DrawerForm>
                  </>
                )}
                <Divider
                  orientation="left"
                  style={{
                    fontWeight: 600,
                    fontSize: 14,
                    marginBottom: -5,
                  }}
                >
                  回复列表
                </Divider>
                <ListReceipt recordId={record?.id} type={2} deadlineTime={''} />
              </>
            )}
          </>
        </WaterMark>
      </Spin>
    </DrawerForm>
  );
};

export default DetailsRecord;
